package com.mazaiting.auth.security.extension.base;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AbstractTokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

/**
 * token 授权基类
 *
 * @author mazaiting
 * @create_time 2022/9/26 23:26
 */
public abstract class BaseTokenGranter extends AbstractTokenGranter {

    private final AuthenticationManager authenticationManager;

    protected BaseTokenGranter(AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory, String grantType, AuthenticationManager authenticationManager) {
        super(tokenServices, clientDetailsService, requestFactory, grantType);
        this.authenticationManager = authenticationManager;
    }


    /**
     * 认证
     * @param client 客户端信息
     * @param tokenRequest 令牌请求
     * @param userAuth 用户认证信息
     * @return 返回 OAuth2Authentication
     */
    public OAuth2Authentication authenticate(ClientDetails client, TokenRequest tokenRequest, Authentication userAuth) {
        try {
            // 认证中
            userAuth = this.authenticationManager.authenticate(userAuth);

            // 认证成功
            if (userAuth != null && userAuth.isAuthenticated()) {
                OAuth2Request storedOAuth2Request = this.getRequestFactory().createOAuth2Request(client, tokenRequest);
                return new OAuth2Authentication(storedOAuth2Request, userAuth);
            } else {
                // 认证失败
                throw new InvalidGrantException("Could not authenticate user: " + userAuth);
            }
        } catch (Exception e) {
            throw new InvalidGrantException(e.getMessage());
        }
    }


}
